package com.bawei.demo_shoppingcar.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bawei.demo_shoppingcar.bean.ShoppingDBbean;

import java.util.ArrayList;


/**
 * Created by HP on 2017/3/22.
 */

public class ShoppingDBUtils {

    private static volatile ShoppingDBUtils instance=null;

    private Context context;
    private final ShoppingDBHelper helper;
    private final String DB_NAME = "shoppingcar";

    public static ShoppingDBUtils getInstance(Context context){
        synchronized(ShoppingDBUtils.class){
            if(instance==null){
                instance=new ShoppingDBUtils(context);
            }
        }
        return instance;
    }



    public ShoppingDBUtils(Context context) {
        this.context = context;
        helper = new ShoppingDBHelper(context);
    }
    //添加
    public void insertData(ShoppingDBbean bean){

        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name_",bean.getShopping_name());
        values.put("price_",bean.getShopping_price());
        values.put("num_",bean.getNum());
        values.put("image_",bean.getShopping_image());
        db.insert(DB_NAME,null,values);

    }

    //查找
    public ArrayList<ShoppingDBbean> queryData (){

        ArrayList<ShoppingDBbean> list = new ArrayList<>();
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor query = db.query(DB_NAME, null, null, null, null, null, null);
        while(query.moveToNext()){
            int id_ = query.getInt(query.getColumnIndex("id_"));
            String name_ = query.getString(query.getColumnIndex("name_"));
            String image_ = query.getString(query.getColumnIndex("image_"));
            double price_ = query.getDouble(query.getColumnIndex("price_"));
            int num_ = query.getInt(query.getColumnIndex("num_"));

            list.add(new ShoppingDBbean(id_,name_,price_,num_,image_));
        }
        return list;
    }

    //删除
    public void deleteData(int id){
        String[] whereValue = { Integer.toString(id) };
        SQLiteDatabase db = helper.getWritableDatabase();
        db.delete(DB_NAME,"id_=?",whereValue);

    }



}
